<?php
/**
 *
 * Created by PhpStorm.
 * User: liangtiehui
 * Date: 2016/4/18
 * Time: 21:01
 */

namespace Observer;

/**
 * 具体主题角色
 * Class ConcreteSubject
 * @package Observer
 */
class ConcreteSubject implements Subject
{

    private $_observers;

    public function __construct()
    {
        $this->_observers = [];
    }

    /**
     * 增加一个观察者对象
     * @param Observer $observer
     * @return mixed
     */
    public function attach(Observer $observer)
    {
        return array_push($this->_observers, $observer);
    }

    /**
     * 删除一个观察者对象
     * @param Observer $observer
     * @return mixed
     */
    public function detach(Observer $observer)
    {
        $index = array_search($observer, $this->_observers);
        if ($index === false || !array_key_exists($index, $this->_observers)) {
            return false;
        }
        unset($this->_observers[$index]);
        return true;
    }

    /**
     * 通知所有观察者对象
     * @return mixed
     */
    public function notifyObservers()
    {
        if (!is_array($this->_observers)) {
            return false;
        }
        foreach($this->_observers as $observer)
        {
            $observer->update();
        }
        return true;
    }
}